What is fast-csv?
The fast-csv npm package is a comprehensive library for working with CSV data in Node.js. It provides functionalities for parsing CSV files and strings, formatting data to CSV, and transforming data during the parse and format process.
What are fast-csv's main functionalities?
Parsing CSV
This feature allows you to parse CSV files or strings. The code sample demonstrates how to read a CSV file using a stream, parse it with headers, and log each row to the console.
const fs = require('fs');
const fastcsv = require('fast-csv');
fs.createReadStream('data.csv')
.pipe(fastcsv.parse({ headers: true }))
.on('data', row => console.log(row))
.on('end', () => console.log('CSV file successfully processed'));
Formatting Data to CSV
This feature allows you to format JavaScript data arrays or streams to CSV. The code sample shows how to take an array of objects and write it to a CSV file with headers.
const fs = require('fs');
const fastcsv = require('fast-csv');
const data = [{ id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }];
fastcsv
.write(data, { headers: true })
.pipe(fs.createWriteStream('out.csv'))
.on('finish', () => console.log('Write to out.csv successfully!'));
Transforming Data
This feature allows you to transform data during the parse or format process. The code sample demonstrates how to read a CSV file, transform each row by combining first and last names into a full name, and then write the transformed data to a new CSV file.
const fs = require('fs');
const fastcsv = require('fast-csv');
fs.createReadStream('data.csv')
.pipe(fastcsv.parse({ headers: true }))
.transform(row => ({ fullName: row.firstName + ' ' + row.lastName }))
.pipe(fastcsv.format({ headers: true }))
.pipe(fs.createWriteStream('out.csv'))
.on('finish', () => console.log('Transformed file successfully written.'));
Other packages similar to fast-csv
papaparse
PapaParse is a robust and powerful CSV parser for JavaScript with a similar feature set to fast-csv. It supports browser and server-side parsing, auto-detection of delimiters, and stream parsing. Compared to fast-csv, PapaParse has a stronger emphasis on browser-side parsing and provides a more user-friendly configuration for handling large files in the browser.
csv-parser
csv-parser is a Node.js module for parsing CSV data. It can handle large datasets and supports stream-based processing. While fast-csv offers both parsing and formatting capabilities, csv-parser focuses primarily on parsing CSV data and may be preferred for its simplicity when only parsing functionality is needed.
csv-writer
csv-writer is a CSV writing library for Node.js that provides functionality to serialize arrays and objects into CSV files. Unlike fast-csv, which offers both parsing and formatting, csv-writer is specialized for CSV output, making it a good choice if the primary requirement is to generate CSV files from data.